from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
import sqlite3
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import secrets
import string
from datetime import datetime, timedelta

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024  # 10MB max file size

# 邮箱配置
# 请在这里配置您的真实邮箱信息
# 邮箱配置 - 推荐使用Gmail或QQ邮箱（Outlook已禁用基本身份验证）
# Gmail配置（推荐）
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME', 'zuozuotools@gmail.com')  # 请配置Gmail邮箱
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD', 'lauw wizj wejk hyik')     # 请配置Gmail应用专用密码

# 如果使用QQ邮箱，请取消下面注释并注释上面Gmail配置
# app.config['MAIL_SERVER'] = 'smtp.qq.com'
# app.config['MAIL_PORT'] = 587
# app.config['MAIL_USE_TLS'] = True
# app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME', 'your-email@qq.com')
# app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD', 'your-qq-auth-code')

# 其他邮箱服务商配置示例：
# QQ邮箱: smtp.qq.com, 端口587, 需要开启SMTP服务并获取授权码
# 163邮箱: smtp.163.com, 端口25/465, 需要开启SMTP服务并获取授权码
# Outlook: smtp-mail.outlook.com, 端口587

# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs('user_tools', exist_ok=True)

# 数据库初始化
def init_db():
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    
    # 用户表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            email TEXT UNIQUE NOT NULL,
            password_hash TEXT NOT NULL,
            is_verified INTEGER DEFAULT 0,
            verification_token TEXT,
            reset_token TEXT,
            reset_token_expires TIMESTAMP,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ''')
    
    # 检查并添加新字段（为现有数据库升级）
    try:
        cursor.execute('ALTER TABLE users ADD COLUMN reset_token TEXT')
    except sqlite3.OperationalError:
        pass  # 字段已存在
    
    try:
        cursor.execute('ALTER TABLE users ADD COLUMN reset_token_expires TIMESTAMP')
    except sqlite3.OperationalError:
        pass  # 字段已存在
    
    # 工具表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS tools (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            description TEXT,
            category TEXT NOT NULL,
            file_path TEXT NOT NULL,
            user_id INTEGER,
            usage_count INTEGER DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users (id)
        )
    ''')
    
    # 检查是否需要插入默认工具数据（只在工具表为空时插入）
    cursor.execute('SELECT COUNT(*) FROM tools')
    tool_count = cursor.fetchone()[0]
    
    if tool_count == 0:
        print("📦 初始化默认工具数据...")
        default_tools = [
            ('PDF转图片', '将PDF文档转换为高质量的JPG、PNG图片格式', '文档处理', 'default/pdf_to_image.html', None, 0),
            ('图片加水印', '为图片添加文字或图片水印', '图像处理', 'default/image_watermark.html', None, 0),
            ('JSON格式化', '美化和格式化JSON数据', '开发助手', 'default/json_formatter.html', None, 0),
            ('2048游戏', '经典数字合并游戏', '小游戏', 'default/game_2048.html', None, 0)
        ]
        
        cursor.executemany('''
            INSERT INTO tools (name, description, category, file_path, user_id, usage_count)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', default_tools)
        print("✅ 默认工具数据初始化完成")
    else:
        print(f"📋 工具表已存在 {tool_count} 个工具，跳过初始化")
    
    conn.commit()
    conn.close()

# 生成验证令牌
def generate_verification_token():
    return ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(32))

# 发送验证邮件
def send_verification_email(email, token):
    # 检查邮箱配置是否完整
    if (app.config['MAIL_USERNAME'] == 'your-email@gmail.com' or 
        app.config['MAIL_PASSWORD'] == 'your-app-password'):
        print("❌ 邮箱配置未完成！请配置真实的邮箱信息")
        print("📝 请查看项目根目录下的'邮箱配置说明.md'文件获取详细配置指南")
        print("⚠️  注意：Outlook已禁用基本身份验证，推荐使用Gmail或QQ邮箱")
        return False
    
    print(f"📧 正在发送验证邮件到: {email}")
    print(f"📤 使用邮箱: {app.config['MAIL_USERNAME']}")
    print(f"🔗 SMTP服务器: {app.config['MAIL_SERVER']}:{app.config['MAIL_PORT']}")
    
    try:
        msg = MIMEMultipart()
        msg['From'] = app.config['MAIL_USERNAME']
        msg['To'] = email
        msg['Subject'] = '个人工具网站集 - 邮箱验证'
        
        verification_link = url_for('verify_email', token=token, _external=True)
        body = f'''
        欢迎注册个人工具网站集！
        
        请点击以下链接验证您的邮箱地址：
        {verification_link}
        
        此链接将在24小时后过期。
        
        如果您没有注册此账户，请忽略此邮件。
        '''
        
        msg.attach(MIMEText(body, 'plain', 'utf-8'))
        
        print("🔄 正在连接SMTP服务器...")
        server = smtplib.SMTP(app.config['MAIL_SERVER'], app.config['MAIL_PORT'])
        server.starttls()
        
        print("🔐 正在进行SMTP认证...")
        server.login(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
        
        print("📨 正在发送邮件...")
        text = msg.as_string()
        server.sendmail(app.config['MAIL_USERNAME'], email, text)
        server.quit()
        
        print("✅ 邮件发送成功！")
        return True
        
    except smtplib.SMTPAuthenticationError as e:
        print(f"❌ SMTP认证失败: {e}")
        print("🔧 解决方案：")
        if 'outlook.com' in app.config['MAIL_SERVER'] or 'hotmail.com' in app.config['MAIL_SERVER']:
            print("   1. 确保使用的是应用专用密码，不是普通登录密码")
            print("   2. 登录 https://account.microsoft.com/security")
            print("   3. 开启两步验证")
            print("   4. 生成应用专用密码并使用该密码")
        else:
            print("   1. 检查邮箱用户名和密码是否正确")
            print("   2. 确保已开启SMTP服务")
            print("   3. 使用应用专用密码而不是普通密码")
        return False
        
    except smtplib.SMTPConnectError as e:
        print(f"❌ SMTP连接失败: {e}")
        print("🔧 解决方案：")
        print("   1. 检查网络连接")
        print("   2. 确认SMTP服务器地址和端口号正确")
        print("   3. 检查防火墙设置")
        return False
        
    except smtplib.SMTPRecipientsRefused as e:
        print(f"❌ 收件人被拒绝: {e}")
        print("🔧 解决方案：")
        print("   1. 检查收件人邮箱地址是否正确")
        print("   2. 确认收件人邮箱服务器是否正常")
        return False
        
    except Exception as e:
        print(f"❌ 邮件发送失败: {e}")
        print("🔧 请检查邮箱配置和网络连接")
        return False

def send_password_reset_email(email, username, token):
    # 检查邮箱配置是否完整
    if (app.config['MAIL_USERNAME'] == 'your-email@gmail.com' or 
        app.config['MAIL_PASSWORD'] == 'your-app-password'):
        print("❌ 邮箱配置未完成！请配置真实的邮箱信息")
        print("📝 请查看项目根目录下的'邮箱配置说明.md'文件获取详细配置指南")
        print("⚠️  注意：Outlook已禁用基本身份验证，推荐使用Gmail或QQ邮箱")
        return False
    
    print(f"📧 正在发送密码重置邮件到: {email}")
    print(f"📤 使用邮箱: {app.config['MAIL_USERNAME']}")
    print(f"🔗 SMTP服务器: {app.config['MAIL_SERVER']}:{app.config['MAIL_PORT']}")
    
    try:
        msg = MIMEMultipart()
        msg['From'] = app.config['MAIL_USERNAME']
        msg['To'] = email
        msg['Subject'] = '个人工具网站集 - 密码重置'
        
        reset_link = url_for('reset_password', token=token, _external=True)
        body = f'''
        您好 {username}，
        
        我们收到了您的密码重置请求。
        
        请点击以下链接重置您的密码：
        {reset_link}
        
        此链接将在24小时后过期。
        
        如果您没有请求重置密码，请忽略此邮件。您的账户仍然安全。
        
        祝好！
        个人工具网站集团队
        '''
        
        msg.attach(MIMEText(body, 'plain', 'utf-8'))
        
        print("🔄 正在连接SMTP服务器...")
        server = smtplib.SMTP(app.config['MAIL_SERVER'], app.config['MAIL_PORT'])
        server.starttls()
        
        print("🔐 正在进行SMTP认证...")
        server.login(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
        
        print("📨 正在发送邮件...")
        text = msg.as_string()
        server.sendmail(app.config['MAIL_USERNAME'], email, text)
        server.quit()
        
        print("✅ 密码重置邮件发送成功！")
        return True
        
    except Exception as e:
        print(f"❌ 密码重置邮件发送失败: {e}")
        print("🔧 请检查邮箱配置和网络连接")
        return False

# 路由定义
@app.route('/')
def index():
    # 获取工具数据
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    
    category = request.args.get('category', '全部工具')
    if category == '全部工具':
        cursor.execute('SELECT * FROM tools ORDER BY usage_count DESC')
    else:
        cursor.execute('SELECT * FROM tools WHERE category = ? ORDER BY usage_count DESC', (category,))
    
    tools = cursor.fetchall()
    
    # 获取分类列表
    cursor.execute('SELECT DISTINCT category FROM tools')
    categories = [row[0] for row in cursor.fetchall()]
    
    conn.close()
    
    return render_template('index.html', tools=tools, categories=categories, current_category=category)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # 支持JSON和表单数据
        if request.is_json:
            data = request.get_json()
            username = data.get('username') if data else None
            password = data.get('password') if data else None
        else:
            username = request.form.get('username')
            password = request.form.get('password')
        
        if not username or not password:
            message = '请填写用户名和密码'
            if request.is_json:
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
                return render_template('login.html')
        
        conn = sqlite3.connect('database.db')
        cursor = conn.cursor()
        cursor.execute('SELECT id, password_hash, is_verified, email FROM users WHERE username = ? OR email = ?', (username, username))
        user = cursor.fetchone()
        conn.close()
        
        if user and check_password_hash(user[1], password):
            if user[2]:  # is_verified
                session['user_id'] = user[0]
                message = '登录成功'
                if request.is_json:
                    return jsonify({'success': True, 'message': message})
                else:
                    flash(message, 'success')
                    return redirect(url_for('index'))
            else:
                message = '请先验证您的邮箱'
                if request.is_json:
                    return jsonify({
                        'success': False, 
                        'message': message,
                        'error_type': 'email_not_verified',
                        'email': user[3]  # 返回邮箱地址用于重新发送验证
                    })
                else:
                    flash(message, 'error')
        else:
            message = '用户名或密码错误'
            if request.is_json:
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
    
    return render_template('login.html')

@app.route('/logout')
def logout():
    session.clear()
    flash('已退出登录', 'success')
    return redirect(url_for('index'))

@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
    if request.method == 'POST':
        # 支持JSON和表单数据
        if request.is_json:
            data = request.get_json()
            email = data.get('email') if data else None
        else:
            email = request.form.get('email')
        
        if not email:
            message = '请输入邮箱地址'
            if request.is_json:
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
                return render_template('forgot_password.html')
        
        # 检查邮箱是否存在
        conn = sqlite3.connect('database.db')
        cursor = conn.cursor()
        cursor.execute('SELECT id, username FROM users WHERE email = ?', (email,))
        user = cursor.fetchone()
        
        if user:
            # 生成密码重置令牌
            reset_token = generate_verification_token()
            # 设置令牌过期时间（24小时后）
            expires_at = datetime.now() + timedelta(hours=24)
            
            # 保存重置令牌到数据库
            cursor.execute('UPDATE users SET reset_token = ?, reset_token_expires = ? WHERE id = ?', 
                         (reset_token, expires_at, user[0]))
            conn.commit()
            
            # 发送密码重置邮件
            if send_password_reset_email(email, user[1], reset_token):
                message = '密码重置邮件已发送，请检查您的邮箱'
                success = True
            else:
                message = '邮件发送失败，请稍后重试'
                success = False
        else:
            # 为了安全，即使邮箱不存在也显示相同消息
            message = '如果该邮箱已注册，您将收到密码重置邮件'
            success = True
        
        conn.close()
        
        if request.is_json:
            return jsonify({'success': success, 'message': message})
        else:
            flash(message, 'success' if success else 'error')
            return redirect(url_for('login'))
    
    return render_template('forgot_password.html')

@app.route('/reset_password/<token>', methods=['GET', 'POST'])
def reset_password(token):
    if request.method == 'GET':
        # 验证令牌是否有效
        conn = sqlite3.connect('database.db')
        cursor = conn.cursor()
        cursor.execute('SELECT id, email, reset_token_expires FROM users WHERE reset_token = ?', (token,))
        user = cursor.fetchone()
        conn.close()
        
        if not user:
            flash('重置链接无效或已过期', 'error')
            return redirect(url_for('forgot_password'))
        
        user_id, email, expires_at = user
        if datetime.now() > datetime.fromisoformat(expires_at):
            flash('重置链接已过期，请重新申请', 'error')
            return redirect(url_for('forgot_password'))
        
        return render_template('reset_password.html', token=token, email=email)
    
    elif request.method == 'POST':
        # 支持JSON和表单数据
        if request.is_json:
            data = request.get_json()
            new_password = data.get('password') if data else None
            confirm_password = data.get('confirm_password') if data else None
        else:
            new_password = request.form.get('password')
            confirm_password = request.form.get('confirm_password')
        
        if not new_password or not confirm_password:
            message = '请填写所有字段'
            if request.is_json:
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
                return render_template('reset_password.html', token=token)
        
        if new_password != confirm_password:
            message = '两次输入的密码不一致'
            if request.is_json:
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
                return render_template('reset_password.html', token=token)
        
        if len(new_password) < 6:
            message = '密码长度至少6位'
            if request.is_json:
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
                return render_template('reset_password.html', token=token)
        
        # 验证令牌并更新密码
        conn = sqlite3.connect('database.db')
        cursor = conn.cursor()
        cursor.execute('SELECT id, reset_token_expires FROM users WHERE reset_token = ?', (token,))
        user = cursor.fetchone()
        
        if not user:
            conn.close()
            message = '重置链接无效或已过期'
            if request.is_json:
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
                return redirect(url_for('forgot_password'))
        
        user_id, expires_at = user
        if datetime.now() > datetime.fromisoformat(expires_at):
            conn.close()
            message = '重置链接已过期，请重新申请'
            if request.is_json:
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
                return redirect(url_for('forgot_password'))
        
        # 更新密码并清除重置令牌
        password_hash = generate_password_hash(new_password)
        cursor.execute('UPDATE users SET password_hash = ?, reset_token = NULL, reset_token_expires = NULL WHERE id = ?', 
                     (password_hash, user_id))
        conn.commit()
        conn.close()
        
        message = '密码重置成功，请使用新密码登录'
        if request.is_json:
            return jsonify({'success': True, 'message': message, 'redirect_url': url_for('login')})
        else:
            flash(message, 'success')
            return redirect(url_for('login'))

@app.route('/tools/category/<category>')
def tools_category(category):
    # 获取指定分类的工具
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM tools WHERE category = ? ORDER BY usage_count DESC', (category,))
    tools = cursor.fetchall()
    
    # 获取所有分类
    cursor.execute('SELECT DISTINCT category FROM tools ORDER BY category')
    categories = [row[0] for row in cursor.fetchall()]
    conn.close()
    
    return render_template('index.html', tools=tools, categories=categories, current_category=category)

@app.route('/resend_verification', methods=['POST'])
def resend_verification():
    # 支持JSON和表单数据
    if request.is_json:
        data = request.get_json()
        email = data.get('email') if data else None
    else:
        email = request.form.get('email')
    
    if not email:
        if request.is_json:
            return jsonify({'success': False, 'message': '邮箱地址不能为空'})
        else:
            flash('邮箱地址不能为空', 'error')
            return redirect(url_for('register'))
    
    # 检查用户是否存在且未验证
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute('SELECT id, is_verified FROM users WHERE email = ?', (email,))
    user = cursor.fetchone()
    
    if not user:
        conn.close()
        message = '该邮箱未注册'
        if request.is_json:
            return jsonify({'success': False, 'message': message})
        else:
            flash(message, 'error')
            return redirect(url_for('register'))
    
    user_id, is_verified = user
    if is_verified:
        conn.close()
        message = '该邮箱已验证，无需重新发送'
        if request.is_json:
            return jsonify({'success': False, 'message': message})
        else:
            flash(message, 'info')
            return redirect(url_for('login'))
    
    # 生成新的验证令牌
    new_token = generate_verification_token()
    cursor.execute('UPDATE users SET verification_token = ? WHERE id = ?', (new_token, user_id))
    conn.commit()
    conn.close()
    
    # 发送验证邮件
    if send_verification_email(email, new_token):
        message = '验证邮件已重新发送，请检查您的邮箱'
        if request.is_json:
            return jsonify({'success': True, 'message': message})
        else:
            flash(message, 'success')
            session['pending_email'] = email
            return redirect(url_for('email_verification'))
    else:
        message = '邮件发送失败，请检查邮箱配置或稍后重试'
        if request.is_json:
            return jsonify({'success': False, 'message': message})
        else:
            flash(message, 'error')
            return redirect(url_for('register'))

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        # 处理JSON和表单数据
        if request.is_json:
            data = request.get_json()
            username = data.get('username')
            email = data.get('email')
            password = data.get('password')
        else:
            username = request.form['username']
            email = request.form['email']
            password = request.form['password']
        
        # 验证输入
        if not username or not email or not password:
            message = '请填写所有字段'
            if request.is_json:
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
                return render_template('register.html')
        
        # 检查用户是否已存在
        conn = sqlite3.connect('database.db')
        cursor = conn.cursor()
        
        # 分别检查用户名和邮箱
        cursor.execute('SELECT id, is_verified FROM users WHERE username = ?', (username,))
        username_exists = cursor.fetchone()
        
        cursor.execute('SELECT id, is_verified FROM users WHERE email = ?', (email,))
        email_exists = cursor.fetchone()
        
        if username_exists:
            message = '用户名已存在，请选择其他用户名'
            conn.close()
            if request.is_json or request.headers.get('Content-Type') == 'application/json':
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
                return render_template('register.html')
        
        if email_exists:
            user_id, is_verified = email_exists
            conn.close()
            if is_verified:
                message = '该邮箱已注册并验证，请直接登录'
                if request.is_json or request.headers.get('Content-Type') == 'application/json':
                    return jsonify({'success': False, 'message': message})
                else:
                    flash(message, 'error')
                    return render_template('register.html')
            else:
                message = '该邮箱已注册但未验证，请检查邮箱或点击下方按钮重新发送验证邮件'
                # 在session中存储邮箱信息，用于重新发送验证
                session['unverified_email'] = email
                if request.is_json or request.headers.get('Content-Type') == 'application/json':
                    return jsonify({
                        'success': False, 
                        'message': message,
                        'show_resend': True,
                        'unverified_email': email
                    })
                else:
                    flash(message, 'warning')
                    return render_template('register.html', show_resend=True, unverified_email=email)
        
        # 创建用户
        password_hash = generate_password_hash(password)
        verification_token = generate_verification_token()
        
        cursor.execute('''
            INSERT INTO users (username, email, password_hash, verification_token)
            VALUES (?, ?, ?, ?)
        ''', (username, email, password_hash, verification_token))
        
        conn.commit()
        conn.close()
        
        # 发送验证邮件
        if send_verification_email(email, verification_token):
            session['pending_email'] = email
            if request.is_json:
                return jsonify({
                    'success': True, 
                    'message': '注册成功！请检查您的邮箱并点击验证链接。',
                    'redirect_url': url_for('email_verification')
                })
            else:
                return redirect(url_for('email_verification'))
        else:
            # 删除刚创建的用户记录，因为邮件发送失败
            conn = sqlite3.connect('database.db')
            cursor = conn.cursor()
            cursor.execute('DELETE FROM users WHERE email = ?', (email,))
            conn.commit()
            conn.close()
            
            message = '邮件发送失败！请检查邮箱配置。详细说明请查看项目根目录下的"邮箱配置说明.md"文件。'
            if request.is_json:
                return jsonify({'success': False, 'message': message})
            else:
                flash(message, 'error')
                flash('常见原因：1. 邮箱配置未完成 2. 网络连接问题 3. 邮箱服务商SMTP未开启', 'info')
    
    return render_template('register.html')

@app.route('/email_verification')
def email_verification():
    email = session.get('pending_email')
    if not email:
        return redirect(url_for('register'))
    return render_template('email_verification.html', email=email)

@app.route('/verify/<token>')
def verify_email(token):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    
    cursor.execute('SELECT id, email FROM users WHERE verification_token = ?', (token,))
    user = cursor.fetchone()
    
    if user:
        cursor.execute('UPDATE users SET is_verified = 1, verification_token = NULL WHERE id = ?', (user[0],))
        conn.commit()
        flash('邮箱验证成功！您现在可以登录了。', 'success')
    else:
        flash('验证链接无效或已过期', 'error')
    
    conn.close()
    return redirect(url_for('index'))

@app.route('/profile')
def profile():
    if 'user_id' not in session:
        flash('请先登录后再访问个人中心', 'error')
        return redirect(url_for('index'))
    
    # 获取用户信息
    user_id = session['user_id']
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    cursor.execute('SELECT username, email FROM users WHERE id = ?', (user_id,))
    user_info = cursor.fetchone()
    conn.close()
    
    if user_info:
        current_user = {
            'username': user_info[0],
            'email': user_info[1]
        }
    else:
        current_user = None
    
    return render_template('profile.html', current_user=current_user)

@app.route('/api/my_tools')
def get_my_tools():
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '请先登录'})
    
    user_id = session['user_id']
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    
    cursor.execute('''
        SELECT id, name, description, category, usage_count, created_at
        FROM tools 
        WHERE user_id = ?
        ORDER BY created_at DESC
    ''', (user_id,))
    
    tools = []
    for row in cursor.fetchall():
        tools.append({
            'id': row[0],
            'name': row[1],
            'description': row[2],
            'category': row[3],
            'usage_count': row[4],
            'created_at': row[5]
        })
    
    conn.close()
    return jsonify({'success': True, 'tools': tools})

@app.route('/api/delete_tool/<int:tool_id>', methods=['DELETE'])
def delete_tool(tool_id):
    if 'user_id' not in session:
        return jsonify({'success': False, 'message': '请先登录'})
    
    user_id = session['user_id']
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    
    # 检查工具是否属于当前用户
    cursor.execute('SELECT file_path FROM tools WHERE id = ? AND user_id = ?', (tool_id, user_id))
    result = cursor.fetchone()
    
    if not result:
        conn.close()
        return jsonify({'success': False, 'message': '工具不存在或无权限删除'})
    
    file_path = result[0]
    
    # 删除数据库记录
    cursor.execute('DELETE FROM tools WHERE id = ? AND user_id = ?', (tool_id, user_id))
    conn.commit()
    conn.close()
    
    # 删除文件
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
    except Exception as e:
        print(f"删除文件失败: {e}")
    
    return jsonify({'success': True, 'message': '工具删除成功'})

@app.route('/upload_tool', methods=['POST'])
def upload_tool():
    try:
        if 'user_id' not in session:
            return jsonify({'success': False, 'message': '请先登录'})
        
        if 'html_file' not in request.files:
            return jsonify({'success': False, 'message': '没有选择文件'})
        
        file = request.files['html_file']
        if file.filename == '':
            return jsonify({'success': False, 'message': '没有选择文件'})
        
        if file and file.filename.lower().endswith(('.html', '.htm')):
            filename = secure_filename(file.filename)
            user_id = session['user_id']
            
            # 创建用户专属目录
            user_dir = os.path.join('user_tools', str(user_id))
            os.makedirs(user_dir, exist_ok=True)
            
            file_path = os.path.join(user_dir, filename)
            file.save(file_path)
            
            # 保存到数据库
            name = request.form.get('tool_name', filename)
            description = request.form.get('description', '')
            category = request.form.get('category', '其他')
            
            conn = sqlite3.connect('database.db')
            cursor = conn.cursor()
            cursor.execute('''
                INSERT INTO tools (name, description, category, file_path, user_id)
                VALUES (?, ?, ?, ?, ?)
            ''', (name, description, category, file_path, user_id))
            conn.commit()
            conn.close()
            
            print(f"✅ 工具上传成功: {name} (用户ID: {user_id})")
            return jsonify({'success': True, 'message': '工具上传成功'})
        
        return jsonify({'success': False, 'message': '只支持HTML文件'})
    
    except Exception as e:
        print(f"❌ 工具上传失败: {str(e)}")
        return jsonify({'success': False, 'message': f'上传失败: {str(e)}'})

@app.route('/tool/<int:tool_id>')
def view_tool(tool_id):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    
    # 更新使用次数
    cursor.execute('UPDATE tools SET usage_count = usage_count + 1 WHERE id = ?', (tool_id,))
    
    # 获取工具信息
    cursor.execute('SELECT file_path FROM tools WHERE id = ?', (tool_id,))
    result = cursor.fetchone()
    
    conn.commit()
    conn.close()
    
    if result:
        file_path = result[0]
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            return content
        except FileNotFoundError:
            return "工具文件不存在", 404
    
    return "工具不存在", 404

if __name__ == '__main__':
    init_db()
    app.run(debug=True, host='0.0.0.0', port=5000)